package com.yc.votesys.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yc.votesys.bean.Topics;
import com.yc.votesys.bean.UserInfo;
import com.yc.votesys.biz.ITopicsService;
import com.yc.votesys.biz.impl.TopicsServiceImpl;
import com.yc.votesys.util.RequestParamUtil;
@WebServlet("/topic/*")
public class TopicsController extends BaseController{

	private static final long serialVersionUID = -4657569605383478849L;

	public void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Object obj = request.getSession().getAttribute("currentLoginUser");
		if(obj == null) {
			this.send(response, 600, "未登录");
			return;
		}
		UserInfo user = (UserInfo) obj;
		Topics topics = RequestParamUtil.getParames(Topics.class, request);
		topics.setUsid(user.getUsid());
		ITopicsService topicsService = new TopicsServiceImpl();
		int result = topicsService.add(topics);
		if(result > 0) {
			this.send(response, 200, "成功");
			return;
		}
		this.send(response, 500, "失败");
	}
	
	/**
	 * 查询所有主题
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void findAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ITopicsService topicsService = new TopicsServiceImpl();
		List<Topics> list = topicsService.findAll();
		if(list == null || list.isEmpty()) {
			this.send(response, 500, "暂无数据");
			return;
		}
		this.send(response, 200, list);
	}
	/**
	 * 根据主题编号，查询主题信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void findByTid(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ITopicsService topicsService = new TopicsServiceImpl();
		String tid = request.getParameter("tid");
		Topics topic = topicsService.findByTid(tid);
		if(topic == null) {
			this.send(response, 300, "暂无数据");
			return;
		}
		this.send(response, 200, topic);
	}
	/**
	 * 根据主题编号，查询主题信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void vote(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Object obj = request.getSession().getAttribute("currentLoginUser");
		if(obj == null) {
			this.send(response, 600, "未登录");
			return;
		}
		UserInfo user = (UserInfo) obj;
		ITopicsService topicsService = new TopicsServiceImpl();
		String tid = request.getParameter("tid");
		String iids = request.getParameter("iids");
		
		int ret = topicsService.update(tid, user.getUsid(), iids);
		if(ret > 0) {
			this.send(response, 200, "投票成功");
			return;
		}
		this.send(response, 500, "投票失败");
	}
}
